import {defineStore} from 'pinia'
import {ref,reactive } from 'vue'
import api from '../api'
import router from '../router'

export const useUserStore = defineStore('userStore', () => {
  const user= ref({
    username:'',
    qid:'',
    token:''
  })

  function getUser(username:string,tag:string,pass:string){
    api.newLogin({
      username:username,
      userpwd:pass,
      nametag:tag
    }).then(res => {
       console.log('完整响应数据:', res); // 输出完整的响应数据
       const customRes = res as unknown as { code: number; message: string ,data:object};
       
       const code = customRes.code?? -1; 
       const message = customRes.message?? '未知错误'; 
       const data = customRes.data as { name: string, qid: string, token: string }?? null;
       if(code===0){
            alert('登陆成功');
            user.value.username=data.name;
            user.value.qid=data.qid;
            user.value.token=data.token;
            router.push({name: 'MainPage'});
       }else{
            alert(message);
       }
    })
  }
  const clearUser=()=>{
    user.value={
      username:'',
      qid:'',
      token:''
    };
  }

  return {user,getUser,clearUser};
},{
  persist: true,
}
)